package com.hkpickup.log;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Enumeration;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.*;

/**
 * Log the request originate information.
 * - Demo how to change the log level, see the /WEB-INF/logging.properties 
 * 
 * @author Ken Sze
 *
 */
@SuppressWarnings("serial")
public class LogMessageServlet extends HttpServlet{
	
	private static final Logger log = Logger.getLogger(LogMessageServlet.class.getName());
	private String responseContentType = "text/html";
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		service(req,resp);
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		service(req,resp);
	}
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String reqInfo = this.logRequest(request);			// log 
		this.doResponse(request, response, reqInfo);		// html
	}

	public void logInfo(String logMsg){
		log.info(logMsg);
	}

	private String logRequest(HttpServletRequest request) throws ServletException, IOException {
		//log.info("######## Incoming message ########");
		//logInfo("URI: " + request.getRequestURI());
		StringBuffer reqInfo = new StringBuffer();
		reqInfo.append("Request URL: ").append(request.getRequestURI());
		reqInfo.append("\n");
		reqInfo.append("Request Method: ").append(request.getMethod());
		reqInfo.append("\n");
		//reqInfo.append("Status Code: ").append(request.get)
		
		StringBuffer reqHeader = new StringBuffer();
		for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
			String name = (String) e.nextElement();
			Enumeration e2 = request.getHeaders(name);
			while (e2.hasMoreElements()) {
				reqHeader.append("\n" + name + ": " + e2.nextElement());
			}
		}
		logInfo("HEADERS:" + reqHeader);
		
		StringBuffer reqQueryData = new StringBuffer();
		if (request.getMethod().equalsIgnoreCase("GET")){
			try {
				reqQueryData.append(request.getQueryString());		
				if (reqQueryData!=null){
					logInfo("QUERY (GET): " + reqQueryData);
					logInfo("DECODE: " + java.net.URLDecoder.decode(reqQueryData.toString()));
				}
			}catch(Exception e){			
			}
		}else{
		// log POST data
			InputStream ins = null;
			try {
				ins = request.getInputStream();
				int ch = ins.read();
				while (ch != -1) {
					reqQueryData.append((char) ch);
					ch = ins.read();
				}

			} finally {
				if (ins != null) {
					ins.close();
					ins = null;
				}
			}
			logInfo("QUERY (POST): " + reqQueryData);
		}
		return reqInfo.append(reqHeader).append(reqQueryData).toString();
	}

	private void doResponse(HttpServletRequest request, HttpServletResponse response, String htmlContent) throws ServletException, IOException {
		StringBuffer respContent =  new StringBuffer();
		
		if (responseContentType != null) {
			response.setContentType(responseContentType);
			logInfo("contentType: " + responseContentType);
		}
		
		respContent.append("<html><body>");
		respContent.append(htmlContent.replace("\n", "<br>")); 
		//respContent.append(""); 
		respContent.append("</body></html>"); 
		

		if (respContent != null) {
			Writer out = null;
			try {
				out = response.getWriter();
				out.write(respContent.toString());
			} finally {
				if (out != null) {
					out.close();
					out = null;
				}
			}
			//logInfo("######## End of message ########");
			//logInfo("");logInfo("");
		}
	}
}
